myApp.controller('ubarrierAutoController', function ($scope, $uibModal, $http, ngDialog, $interval, $filter) {
    $scope.info = {};

    //全部zone列表
    $scope.info.zones = [];
    //环境列表
    $scope.info.env = uBarrierEnv;
    //当前选中的环境
    $scope.info.env_name = $scope.info.env[0];
    //是否授权生产发布
    $scope.info.isAuthorize = false;
    //当前选中的zone
    $scope.info.selectZone = {};

    $scope.info.logHtml = '';
    $scope.info.logIds = '';

    //定时器
    $scope.timer = null;
    $scope.authorizeTimer = null;
    $scope.logTimer = null;

    $scope.log_Socket = null;

    $scope.info.checkStatus = "common";
    $scope.info.gaStatus = "common";
    $scope.info.ganStatus = "common";
    $scope.info.gbStatus = "common";
    $scope.info.gbnStatus = "common";

    $scope.$on("$destroy", function () {
        $scope.cleanTimer(true);
        if ($scope.log_Socket != null) {
            $scope.log_Socket.close();
        }
    });

    $scope.cleanTimer = function (flag) {
        console.log("清除项目定时器;");
        if ($scope.timer != null) {
            $interval.cancel($scope.timer);
            $scope.timer = null;
        }
        if (flag && $scope.authorizeTimer != null) {
            $interval.cancel($scope.authorizeTimer);
            $scope.authorizeTimer = null;
        }
        if (flag && $scope.logTimer != null) {
            $interval.cancel($scope.logTimer);
            $scope.logTimer = null;
        }
    };

    $scope.getAuthorize = function () {
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/getAuthorize",
            data: {tokenId: getTokenId()},
            dataType: "JSON",
            async: true,
            success: function (data) {
                $scope.info.isAuthorize = data.data.authorize;
            },
            complete: function (xhr, status) {
            }
        });
    };

    $scope.startAuthorizeTimer = function () {
        if ($scope.info.env_name == 'online' && $scope.authorizeTimer == null) {
            $scope.getAuthorize();
            $scope.authorizeTimer = $interval(function () {
                $scope.getAuthorize();
            }, 3000);
        }
        if ($scope.info.env_name != 'online' && $scope.authorizeTimer != null) {
            $interval.cancel($scope.authorizeTimer);
        }
    };
    var logDiv = document.getElementById("log_div");
    $scope.getLog = function () {
        $http.get(uBarrier_url + '/log/?env_name=' + $scope.info.env_name + '&zone_code=' + $scope.info.selectZone.zone_code).success(function (data) {
            if (data.success && data.data.length > 0 && data.data[0].zone_code == $scope.info.selectZone.zone_code && data.data[0].env_name == $scope.info.selectZone.env_name) {
                angular.forEach(data.data, function (log) {
                    if ($scope.info.logIds.indexOf(log.id) == -1) {
                        console.log(log);
                        $scope.info.logIds = $scope.info.logIds + log.id + ',';
                        var message = "<div>" + $filter('date')(log.create_time, "yyyy-MM-dd HH:mm:ss", 'UTC') + "<span style='margin-left: 20px;color: " + log.color + ";'>" + log.log + "</span>";
                        $scope.handelStatus(log.log);
                        if (log.show_error != null && log.show_error == '0') {
                            message += '<a href="javascript:void(0)" ng-click="ubarrierShowError(\'' + log.env_name + '\',\'' + log.zone_code + '\',\'' + log.group + '\',\'' + log.entrance_types + '\')">点击查看异常信息</a></div>';
                        } else {
                            message += '</div>';
                        }
                        if (log.br_count != 0) {
                            for (var i = 0; i < log.br_count; i++) {
                                message += "<br>"
                            }
                        }
                        $scope.info.logHtml += message;
                        setTimeout(function () {
                            logDiv.scrollTop = logDiv.scrollHeight;
                        }, 50);
                    }
                });
            }
        })
    };

    function logSocket() {
        $scope.log_Socket = io.connect('http://' + uBarrier_config_ip + '/notify', {'forceNew': true});
        $scope.log_Socket.on("stat", function (msg) {
            var data = msg.data.replace(new RegExp(/(None)/g), "''");
            if (data == 'Connected') {
                return;
            }
            data = eval("(" + data + ")");
            if (data.NotifyEvent == $scope.info.env_name + '_' + $scope.info.selectZone.zone_code + '_log') {
                $scope.$apply(function () {
                    if ($scope.info.logIds.indexOf(data.id) == -1) {
                        console.log(data);
                        $scope.info.logIds = $scope.info.logIds + data.id + ',';
                        var message = "<div>" + $filter('date')(data.create_time, "yyyy-MM-dd HH:mm:ss", 'UTC') + "<span style='margin-left: 20px;color: " + data.color + ";'>" + data.log + "</span>";

                        $scope.handelStatus(data.log);

                        if (data.show_error != null && data.show_error == '0') {
                            message += '<a href="javascript:void(0)" ng-click="ubarrierShowError(\'' + data.env_name + '\',\'' + data.zone_code + '\',\'' + data.group + '\',\'' + data.entrance_types + '\')">点击查看异常信息</a></div>';
                        } else {
                            message += '</div>';
                        }
                        if (data.br_count != 0) {
                            for (var i = 0; i < data.br_count; i++) {
                                message += "<br>"
                            }
                        }
                        $scope.info.logHtml += message;
                        setTimeout(function () {
                            logDiv.scrollTop = logDiv.scrollHeight;
                        }, 50);
                    }
                });
            }
        });
    };

    //根据返回的信息处理按钮颜色
    $scope.handelStatus = function (log) {
        if(log.indexOf('校验成功') != -1){
            $scope.info.checkStatus = 'success';
        }else if(log.indexOf('校验失败') != -1){
            $scope.info.checkStatus = 'error';
        }

        if(log.indexOf('A组备用成功') != -1){
            $scope.info.gaStatus = 'success';
        }else if(log.indexOf('A组备用失败') != -1){
            $scope.info.gaStatus = 'error';
        }

        if(log.indexOf('A组取消备用成功') != -1){
            $scope.info.ganStatus = 'success';
        }else if(log.indexOf('A组取消备用失败') != -1){
            $scope.info.ganStatus = 'error';
        }

        if(log.indexOf('B组备用成功') != -1){
            $scope.info.gbStatus = 'success';
        }else if(log.indexOf('B组备用失败') != -1){
            $scope.info.gbStatus = 'error';
        }

        if(log.indexOf('B组取消备用成功') != -1){
            $scope.info.gbnStatus = 'success';
        }else if(log.indexOf('B组取消备用失败') != -1){
            $scope.info.gbnStatus = 'error';
        }
    };

    logSocket();
    // $scope.startLogTimer = function () {
    //     if ($scope.logTimer == null) {
    //         $scope.getLog();
    //         $scope.logTimer = $interval(function () {
    //             $scope.getLog();
    //         }, 3000);
    //     }
    // };
    // $scope.startLogTimer();
    //按钮是否可操作
    $scope.btnPower = function () {
        //1、用户角色包括ubarrier才能操作
        if (!arrayContains(getUserRole(), 'ubarrier_admin')) {
            return false;
        }
        //2、生产环境需要授权
        if ($scope.info.env_name == 'online') {
            if (!$scope.info.isAuthorize) {
                return false;
            }
        }
        return true;
    };

    $scope.getZones = function () {
        $scope.info.zones = [];
        $http.get(uBarrier_url + '/zones/?env_name=' + $scope.info.env_name).success(function (data) {
            if (data.success) {
                $scope.info.zones = data.data;
                $scope.info.selectZone = data.data[0];
                $scope.getLog();
            } else {
                alert(data.msg);
            }
        })
    };

    //初始化方法  切换环境时用
    $scope.init = function () {
        $scope.startAuthorizeTimer();
        $scope.info.logHtml = '';
        $scope.info.logIds = '';
        $scope.getZones();
    };
    $scope.init();
    $scope.clickZone = function (zone) {
        $scope.cleanTimer(false);
        $scope.info.logHtml = '';
        $scope.info.logIds = '';
        $scope.info.selectZone = zone;
        $scope.getLog();
    };
    //资源校验
    $scope.check = function () {
        if (!$scope.btnPower()) {
            alert("没有访问权限，请联系管理员！");
            return;
        }
        openDialog(ngDialog, $scope, "确认要检查当前区域?", true, function (val) {
            if (!val) {
                return;
            }
            doBeetleGet($http, $uibModal, uBarrier_url + '/switch/check?token_id=' + getTokenId() + '&env_name=' + $scope.info.env_name + '&zone_code=' + $scope.info.selectZone.zone_code, function (data) {
                if (!data.success) {
                    alert(data.msg);
                } else {
                    // $scope.getLog();
                }
            });
        });
    };
    //切换
    $scope.doSwitch = function (status, group) {
        if (!$scope.btnPower()) {
            alert("没有访问权限，请联系管理员！");
            return;
        }
        openDialog(ngDialog, $scope, "确认要切换当前区域?", true, function (val) {
            if (!val) {
                return;
            }
            var data = {
                'status': status,
                'env_name': $scope.info.env_name,
                'zone_code': $scope.info.selectZone.zone_code,
                'group': group
            };
            doBeetlePost($http, $uibModal, uBarrier_url + '/switch/autoSwitch', data, function (data) {
                if (!data.success) {
                    alert(data.msg);
                } else {
                    // $scope.getLog();
                }
            });
        });
    };
    $scope.ubarrierShowError = function (env_name, zone_code, group, entrance_type) {
        var info = {};
        info.env_name = env_name;
        info.zone_code = zone_code;
        if (group == 'null') {
            info.group = null;
        } else {
            info.group = group;
        }
        if (entrance_type == 'null') {
            info.entrance_type = null;
        } else {
            info.entrance_type = entrance_type;
        }
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'autoShowError.html',
            controller: 'autoShowErrorCtrl',
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
    };

    $scope.gotoRelease = function () {
        window.location.href = "#/menu/deploy";
    }
});
myApp.controller('autoShowErrorCtrl', function ($scope, $uibModal, $uibModalInstance, info, $http) {
    $scope.info = info;
    $scope.info.appList = [];
    $scope.total = $scope.info.appList.length;

    $scope.page = {size: 15, index: 1};

    $scope.getApps = function () {
        var url = uBarrier_url + '/apps/?env_name=' + $scope.info.env_name + '&current_status=OUT_OF_SERVICE&is_resource=0&zone_code=' + $scope.info.zone_code;
        if ($scope.info.entrance_type != null) {
            url = url + '&entrance_types=' + $scope.info.entrance_type;
        }
        // if (info.group != null) {
        //     url = url + '&group=' + $scope.info.group
        // }
        $http.get(url).success(function (data) {
            if (data.success) {
                angular.forEach(data.data, function (app) {
                    $scope.info.appList.push(app);
                })
            } else {
                alert(data.msg);
            }
        });
    };

    $scope.getEntrance = function (entrance_types) {
        var url = uBarrier_url + '/entrance/?env_name=' + $scope.info.env_name + '&current_status=OUT_OF_SERVICE&zone_codes=' + $scope.info.zone_code + '&types=' + entrance_types;
        $http.get(url).success(function (data) {
            if (data.success) {
                angular.forEach(data.data, function (app) {
                    $scope.info.appList.push(app);
                })
            } else {
                alert(data.msg);
            }
        });
    };

    if ($scope.info.entrance_type == null) {
        $scope.getEntrance('uschedule,haproxy');
        $scope.getApps();
    } else if ($scope.info.entrance_type == 'jmx' || $scope.info.entrance_type == 'hosts') {
        $scope.getApps();
    } else {
        $scope.getEntrance($scope.info.entrance_type);
    }

    $scope.selectError = function (app) {
        var info = {};
        info = app;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'autoError.html',
            controller: 'autoErrorCtrl',
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
    };
    $scope.cancel = function () {
        // 关闭弹出框
        $uibModalInstance.dismiss('cancel');
    };

});

myApp.controller('autoErrorCtrl', function ($scope, $uibModalInstance, info, $http) {
    $scope.info = {};
    $scope.info.msg = "";
    if (info.error_desc != null) {
        $scope.info.msg = info.error_desc;
    } else {
        var str = "";
        if (info.expect_status == "GA") {
            str = "A组进入灰度"
        } else if (info.expect_status == "GB") {
            str = "B组进入灰度"
        } else if (info.expect_status == "GNONE") {
            str = "恢复生产"
        } else if (info.expect_status == "READY") {
            str = "校验状态"
        }

        $scope.info.msg = "切换状态异常，当前状态:" + info.current_status + ",期望状态:" + str;
    }

    $scope.cancel = function () {
        // 关闭弹出框
        $uibModalInstance.dismiss('cancel');
    };
});